package com.well.kernel.exception;

import com.well.kernel.spring.web.ResponseData;
import com.well.kernel.util.WebUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Copyright &copy; Well All rights reserved.
 * Author:Well
 * Date:2017/1/13
 * Description:
 */

@Component
public class HandlerException implements HandlerExceptionResolver {
    private static Logger logger=Logger.getLogger(HandlerException.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        logger.error(e);
        /* 判断是否为 ajax 请求 */
        if(WebUtil.isAjax(request)) // 如果是 ajax 请求
        {
            response.setHeader("exception","exception");
            ResponseData responseData=new ResponseData();
            responseData.setSuccess(false);
            String message="操作异常！";
            if(e instanceof BusinessException){
                message=e.getMessage();
            }
            responseData.setMessage(message);
            WebUtil.renderResponseData(response, responseData);
            return null;
        }
        return new ModelAndView("error/500");
    }
}
